﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Deepforest.TweetMe.UI
{
    internal static class PasswordBoxExtenstions
    {
        public static bool? GetIsEmpty(DependencyObject obj)
        {
            return (bool?)obj.GetValue(IsEmptyProperty);
        }

        public static void SetIsEmpty(DependencyObject obj, bool? value)
        {
            obj.SetValue(IsEmptyProperty, value);
        }

        // Using a DependencyProperty as the backing store for IsEmpty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsEmptyProperty =
            DependencyProperty.RegisterAttached(
                "IsEmpty",
                typeof(bool?),
                typeof(PasswordBoxExtenstions),
                new UIPropertyMetadata(null, null, CoerceIsEmptyProperty));

        private static object CoerceIsEmptyProperty(DependencyObject d, object valueBase)
        {
            var passwordBox = d as PasswordBox;
            if (passwordBox == null)
            {
                throw new NotSupportedException();
            }

            if (valueBase == null)
            {
                // First initialization
                passwordBox.PasswordChanged += passwordBox_PasswordChanged;
                return string.IsNullOrEmpty(passwordBox.Password);
            }

            return valueBase;
        }        

        static void passwordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            var passwordBox = sender as PasswordBox;
            SetIsEmpty(passwordBox, string.IsNullOrEmpty(passwordBox.Password));
        }
    }
}
